//
//  PermenantThread.m
//  MobileBank
//
//  Created by ylj on 2022/5/23.
//

#import "PermenantThread.h"

#pragma mark YHThread class
@implementation YHThread

- (void)dealloc
{
    NSLog(@"%s", __func__);
}

@end


#pragma mark PermenantThread class
@implementation PermenantThread

- (instancetype)init
{
    if (self = [super init]) {
        if (@available(iOS 10.0, *)) {
            self.innerThread = [[YHThread alloc] initWithBlock:^{
                // 创建上下文（要初始化一下结构体）
                CFRunLoopSourceContext context = {0};
                // 创建source
                CFRunLoopSourceRef source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context);
                // 往Runloop中添加source
                CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
                // 销毁source
                CFRelease(source);
                // 启动
                CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e10, false);
            }];
        } else {
            // Fallback on earlier versions
        }
        
        [self.innerThread start];
    }
    return self;
}


- (void)executeTask:(PermenantThreadTask)task
{
    if (!self.innerThread || !task) return;
    
    [self performSelector:@selector(__executeTask:) onThread:self.innerThread withObject:task waitUntilDone:NO];
}

- (void)stop
{
    if (!self.innerThread) return;
    
    [self performSelector:@selector(__stop) onThread:self.innerThread withObject:nil waitUntilDone:YES];
}

- (void)dealloc
{
    NSLog(@"%s", __func__);
    
    [self stop];
}

#pragma mark - private methods
- (void)__stop
{
    CFRunLoopStop(CFRunLoopGetCurrent());
    self.innerThread = nil;
}

- (void)__executeTask:(PermenantThreadTask)task
{
    task();
}

@end

//使用
//JXBPermenantThread *jxbThread = [[JXBPermenantThread alloc] init];
//    [jxbThread executeTask:^{
//        NSLog(@"已经进入后台---执行任务--- %@", [NSThread currentThread]);
//    }];
